import { createRouter, createWebHistory } from 'vue-router'

import index from '@/views/index'
import login from "@/views/login";
import useradd from "@/views/user/add";
import userlist from "@/views/user/list";
import config from "@/views/system/config";
// 创建路由实例对象
const router = createRouter({
    history: createWebHistory(),
    routes: [

        //isAuth:自定义的字段
        { path: '/', name:'index',component:index,

            meta:{
                isAuth:true, //true:必须登录才能访问
                title:'首页'
            },
            children:[
                {path:'/',redirect:'userlist'},
                {path:'user/add',name:'useradd',component:useradd},
                {path:'userlist',name:'userlist',component:userlist},
                {path:'config',name:'config',component:config},
            ]
        },
        { path: '/login', name:'login',component:login,
            meta:{
                isAuth:false, //不用登录就可以访问
                title:'登录页'
            }
        }

    ],
})



// 全局路由导航守卫
router.beforeEach((to, from, next) => {
    console.log(to.meta.isAuth)
    if(to.meta.isAuth){ //true需要验证
        // 获取 token 值
        const user = localStorage.getItem('user')

        if (!user) {
            next('/login')
        } else {
            next()
        }
    }else{
        next()
    }

})

router.afterEach((to)=>{
    if(to.meta.title) {
        document.title = to.meta.title //修改网页的title
    }else {
        document.title = '欢迎访问'
    }
})

export default router
